const { app, BrowserWindow } = require('electron')
const puppeteer = require('puppeteer')
const path = require('path')
require('./ipc')

// 在应用启动前就设置调试端口
const setupDebugPort = () => {
  console.log('正在设置远程调试端口...')
  app.commandLine.appendSwitch('remote-debugging-port', '9222')
  app.commandLine.appendSwitch('ignore-certificate-errors')
  // 添加更多调试相关的开关
  app.commandLine.appendSwitch('disable-features', 'OutOfBlinkCors')
  app.commandLine.appendSwitch('disable-site-isolation-trials')
}

// 立即调用
setupDebugPort()

function createWindow() {
  const win = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      contextIsolation: true,
      nodeIntegration: false,
      webviewTag: true,
      webSecurity: false,
      preload: path.join(__dirname, 'preload/index.js')
    }
  })

  if (process.env.VITE_DEV_SERVER_URL) {
    win.loadURL(process.env.VITE_DEV_SERVER_URL)
    win.webContents.openDevTools()
  } else {
    win.loadFile(path.join(__dirname, '../dist/index.html'))
  }

  // 添加窗口加载完成的监听
  win.webContents.on('did-finish-load', async () => {
    console.log('窗口加载完成，检查调试端口...')
    // 验证调试端口是否可用
    fetch('http://localhost:9222/json/version')
      .then(response => response.json())
      .then(data => {
        console.log('调试端口已就绪:', data)
      })
      .catch(error => {
        console.error('调试端口检查失败:', error)
      })
    const browser = await puppeteer.connect({
        browserURL: 'http://localhost:9222',
        defaultViewport: null,
        ignoreHTTPSErrors: true
    })
    if (browser) {
        console.log("================= puppeteer:连接成功 ==================");
        // 将它挂到app下
        app.puppeteer = browser
    }
  })

  return win
}

// 确保应用完全准备好再创建窗口
let mainWindow = null
app.whenReady().then(() => {
  console.log('应用准备就绪，创建主窗口...')
  mainWindow = createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      mainWindow = createWindow()
    }
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// 添加未捕获异常的处理
process.on('uncaughtException', (error) => {
  console.error('未捕获的异常:', error)
})

process.on('unhandledRejection', (error) => {
  console.error('未处理的 Promise 拒绝:', error)
}) 